//
//  RegisteViewController.m
//  wangzhe
//
//  Created by 李 佳伟 on 2017/10/12.
//  Copyright © 2017年 李 佳伟. All rights reserved.
//

#import "RegisteViewController.h"
#import "JTCSM.h"
#import "TextAndImageView.h"
#import "MyLayout.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "WebViewController.h"

#define DefaultLocationTimeout 10
#define DefaultReGeocodeTimeout 5




@interface RegisteViewController ()<UITextFieldDelegate,AMapLocationManagerDelegate>
{
    NSString *phoeNumber ;
    NSString *passWord ;
    NSString *passWord1 ;
    NSString *code ;
    NSString *barcode;
    NSString *reciveCode;
    NSTimer* _timer1;
    NSTimer* _timer2;
    NSInteger count ;
    UILabel *forgetPassWordLabel;
    NSString *province;
    NSString *city;
    NSString *district;
    NSString *street;
    NSString *lat;
    NSString *lng;
    UITextField *beginTextfield;

}

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;

@end

@implementation RegisteViewController

#pragma mark - Action Handle

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];

}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
}


#pragma mark - Initialization

- (void)initCompleteBlock
{
    __weak RegisteViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            [df showAlertWithTitle:@"请允许王者管家需要访问您的地理位置" message:@"设置->隐私->定位服务->王者管家" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        else if (error != nil && error.code == AMapLocationErrorRiskOfFakeLocation)
        {
            //存在虚拟定位的风险：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else
        {
            //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
        }
        
        //修改label显示内容
        if (regeocode)
        {
//            [weakSelf.displayLabel setText:[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
            province = regeocode.province;
            city = regeocode.city;
            district = regeocode.district;
            street = regeocode.street==nil?@"":regeocode.street;
            lat = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
            lng = [NSString stringWithFormat:@"%f",location.coordinate.longitude];

            
        }
    };
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    province = @"";
    city = @"";
    district = @"";
    street = @"";
    lat = @"";
    lng = @"";
    barcode=@"";
//    [self initCompleteBlock];
//
//    [self configLocationManager];

    // Do any additional setup after loading the view.
    CGFloat imageSize = (KSCREENWidth ==320)?100:113;
    CGFloat ImageTop = (KSCREENWidth ==320)?80:100;
    UIImageView *logoImageV  = [[UIImageView alloc]initWithFrame:CGRectMake((KCONTROLLERWith-imageSize)/2, ImageTop, imageSize, imageSize)];
    logoImageV.image = [UIImage imageNamed:@"loginLOGO.png"];
    [self.view addSubview:logoImageV];
    
    NSArray *textArr = @[@"请输入手机号",@"输入短信验证码",@"输入登录密码"];
    CGFloat space = 20;
    CGFloat theViewTop = ImageTop+imageSize-20+50;
    CGFloat theViewHeight = (KSCREENWidth ==320)?30:40;
    TextAndImageView *theView;
    for (int i = 0 ; i < textArr.count; i++) {
        theView = [[TextAndImageView alloc]initWithFrame:CGRectMake(space, theViewTop+(theViewHeight+20)*i, KCONTROLLERWith-2*space, theViewHeight) withImagename:nil text:textArr[i]];
        theView.textField.delegate = self;
        theView.tag = 1000+i;
        if (i == 1) {
            NSString *string = @"点击获取";
            float font = 15;
            CGFloat labelHeight = 30;
            CGRect rect = [df labelHeightWithContent:string height:labelHeight font:font];
            CGFloat trueheight = rect.size.height+15;
            forgetPassWordLabel = [UILabel initWithFrame:CGRectMake(theView.frame.size.width-10-rect.size.width-10, (theView.frame.size.height-trueheight-10)/2, rect.size.width+10, trueheight) text:string font:font textAlignment:NSTextAlignmentCenter texcolor:RGBACOLOR(193, 193, 193, 1) backgroundColor:nil];
            [df addTapGestureRecognizerWithTarget:self action:@selector(getCode) andaddView:forgetPassWordLabel];
            forgetPassWordLabel.userInteractionEnabled = YES;
            [theView addSubview:forgetPassWordLabel];
            [df layerWithView:forgetPassWordLabel radius:forgetPassWordLabel.LC_height/2 width:1 color:KZhuTiRGB];
        }
        
        [self.view addSubview:theView];
        [self getKeyboardPodWithTextfield:theView.textField];

        
    }
    CGFloat btnspace = 20;
    CGFloat btnHeight = 50;
    UIButton *LoginBtn =[[UIButton alloc] initWithFrame:CGRectMake(btnspace, KVIEW_Y(theView)+60 , (KCONTROLLERWith-2*btnspace), btnHeight)];
    LoginBtn.backgroundColor =KZhuTiRGB;
    [LoginBtn setTitle:@"完成" forState:UIControlStateNormal];
    [LoginBtn setTitleColor:[df colorWithHexString:@"333333" alpha:1] forState:UIControlStateNormal];
    LoginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [LoginBtn addTarget:self action:@selector(gotoMainV) forControlEvents:UIControlEventTouchUpInside];
    LoginBtn.tag = 10002;
    [self.view addSubview:LoginBtn];
    [df layerWithView:LoginBtn radius:7 width:0 color:nil];
    
    UILabel *_zhifuTypeLabel = [UILabel initWithFrame:CGRectZero text:@"" font:15 textAlignment:NSTextAlignmentCenter texcolor:[df colorWithHexString:@"cccccc" alpha:1] backgroundColor:nil];
    [self.view addSubview:_zhifuTypeLabel];
    
    UILabel *changeLabel = [UILabel initWithFrame:CGRectZero text:@"立即登录" font:15 textAlignment:NSTextAlignmentLeft texcolor:[df colorWithHexString:@"333333" alpha:1] backgroundColor:nil];
    [self.view addSubview:changeLabel];
    UIView *changeLineView = [[UIView alloc]initWithFrame:CGRectZero];
    changeLineView.backgroundColor = [df colorWithHexString:@"333333" alpha:1];
    [self.view addSubview:changeLineView];
    NSString *text = @"已有账号，";
    CGRect bottomrect = [df labelHeightWithContent:text width:1000 font:15];
    CGRect rect1 = [df labelHeightWithContent:changeLabel.text width:1000 font:15];
    CGFloat changespace = (KCONTROLLERWith-bottomrect.size.width-rect1.size.width-5)/2;
    _zhifuTypeLabel.text = text;
    _zhifuTypeLabel.frame = CGRectMake(changespace, KVIEW_Y(LoginBtn)+20, bottomrect.size.width, bottomrect.size.height);
    changeLabel.frame = CGRectMake(KVIEW_X(_zhifuTypeLabel)+5, KVIEW_Y(LoginBtn)+20, rect1.size.width, bottomrect.size.height);
    changeLineView.frame = CGRectMake(changeLabel.LC_x, changeLabel.LC_y+changeLabel.LC_height, changeLabel.LC_width, 1);
    changeLabel.userInteractionEnabled = YES;
    [df addTapGestureRecognizerWithTarget:self action:@selector(gotoRegister) andaddView:changeLabel];

}
- (void)getCode{
    NSLog(@"----------");
    [self.view endEditing:YES];
    
    LoadData *request = [[LoadData alloc]init];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    [dict setObject:@"register" forKey:@"do"];
    NSLog(@"%@",phoeNumber);
    if (phoeNumber != nil) {
         [dict setObject:phoeNumber forKey:@"mobile"];
    }
   
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"PassPort/smscode") withDict:dict superView:self.view isAddtag:NO Block:^(id result) {
        
       
        
        NSLog(@"*********************%@",result);
        if (result == nil ) {
            [df showAlertWithTitle:@"获取验证码失败" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
            return ;
        }
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            [self gettime];
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }
        [forgetPassWordLabel setText:@"获取验证码"];
        
    }];
    

    
}
- (void)gotoRegister{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
//    LoadData *request = [[LoadData alloc]init];
//    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"Article/agreement") withDict:nil superView:self.view isAddtag:NO Block:^(id result) {
//        NSLog(@"%@",result);
//
//        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
//        if ([isreturn isEqualToString:@"1"]) {
//
//            NSDictionary *dict = [result objectForKey:@"data"];
//
//            NSString *value = [dict objectForKey:@"content"];
//            NSString *title = [dict objectForKey:@"title"];
//
//            [StorageUtil writeToFile:@"web.html" data:value];
//            WebViewController *vc = [[WebViewController alloc]init];
//            vc.titleName = title;
//            vc.htmlName = [StorageUtil formatPath:@"web.html"];
//            [self.navigationController pushViewController:vc animated:YES];
//
//        }else{
//
//        }
//
//
//    }];
}
- (void)gotoMainV{
    [self.view endEditing:YES];
    
    if ([phoeNumber isEqualToString:@""] || phoeNumber == nil) {
        [df showAlertWithTitle:@"用户名不能为空" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        return;
    }
    if ([passWord isEqualToString:@""] || passWord == nil) {
        [df showAlertWithTitle:@"密码不能为空" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        return;
    }
    if (![passWord1 isEqualToString:passWord]) {
        [df showAlertWithTitle:@"两次密码不一致" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        return;
    }
    
    NSLog(@"%@---%@",passWord,passWord1);
    LoadData *request = [[LoadData alloc]init];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    [dict setObject:phoeNumber forKey:@"mobile"];
    [dict setObject:passWord forKey:@"password"];
    [dict setObject:passWord1 forKey:@"password2"];
    [dict setObject:lat == nil?@"":lat forKey:@"lat"];
    [dict setObject:lng == nil?@"":lng forKey:@"lng"];
    [dict setObject:province == nil?@"":province forKey:@"province"];
    [dict setObject:city == nil?@"":city forKey:@"city"];
    [dict setObject:district == nil?@"":district forKey:@"district"];
    [dict setObject:street == nil?@"":street forKey:@"street"];
    [dict setObject:barcode==nil?@"":barcode forKey:@"barcode"];
    [dict setObject:reciveCode == nil?@"":reciveCode forKey:@"invite"];
    [dict setObject:code forKey:@"code"];
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"PassPort/register") withDict:dict superView:self.view isAddtag:NO  Block:^(id result) {
        NSLog(@"%@",result);
        if (result == nil ) {
            [df showAlertWithTitle:@"注册失败" message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
            return ;
        }
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            NSDictionary *dict = [result objectForKey:@"data"];
            KUSERDEFAULTSET(dict, KInfoKey);
            NSLog(@"%@",KTokenString);
//            [JPUSHService setAlias:[df getMd5_32Bit_String:[NSString stringWithFormat:@"%@Users",KTokenString]]
//                  callbackSelector:@selector(tagsAliasCallback:tags:alias:)
//                            object:self];
            
//            [self gotBack];
            [self.delegate gotoTheMainViewController];
        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }
    }];

}

- (void)getKeyboardPodWithTextfield:(UITextField *)textfield{
    
    TextAndImageView *theView = [self.view viewWithTag:1000];
    TextAndImageView *theView2 = [self.view viewWithTag:1001];
    TextAndImageView *theView3 = [self.view viewWithTag:1002];
    TextAndImageView *theView4 = [self.view viewWithTag:1003];
    TextAndImageView *theView5 = [self.view viewWithTag:1004];
    TextAndImageView *theView6 = [self.view viewWithTag:1005];

    
    if (textfield == theView.textField || textfield == theView2.textField || textfield == theView5.textField||textfield==theView6.textField) {
        textfield.keyboardType = UIKeyboardTypePhonePad;
    }
    if (textfield == theView3.textField||textfield == theView4.textField) {
        textfield.secureTextEntry = YES;
    }
    
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    beginTextfield = textField;
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
    TextAndImageView *theView = [self.view viewWithTag:1000];
    TextAndImageView *theView2 = [self.view viewWithTag:1001];
    TextAndImageView *theView3 = [self.view viewWithTag:1002];
    TextAndImageView *theView4 = [self.view viewWithTag:1003];
    TextAndImageView *theView5 = [self.view viewWithTag:1004];
    TextAndImageView *theView6 = [self.view viewWithTag:1005];

    if (textField == theView.textField) {
        phoeNumber = textField.text;
    }
    if (textField == theView2.textField) {
        code = textField.text;
    }
    if (textField == theView3.textField) {
        passWord = textField.text;
    }
    if (textField == theView4.textField) {
        passWord1 = textField.text;
    }
    if (textField == theView5.textField) {
        barcode = textField.text;
    }
    if (textField == theView6.textField) {
        reciveCode = textField.text;
    }
    
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder] ;
    return YES;
}

- (void)removeKeyBoard{
    [self.view endEditing:YES];
}
#pragma mark --定时器
- (void)gettime{
    [_timer2 invalidate];
    [_timer1 invalidate];
    
    count = 0;
    
    NSTimer* timer=[NSTimer scheduledTimerWithTimeInterval:60
                                                    target:self
                                                  selector:@selector(showRepeatButton)
                                                  userInfo:nil
                                                   repeats:YES];
    
    NSTimer* timer2=[NSTimer scheduledTimerWithTimeInterval:1
                                                     target:self
                                                   selector:@selector(updateTime)
                                                   userInfo:nil
                                                    repeats:YES];
    _timer1=timer;
    _timer2=timer2;
    
}
-(void)updateTime{
    count++;
    if (count>180)
    {
        [_timer2 invalidate];
        return;
    }
    NSString *timeStr=[NSString stringWithFormat:@"%lus重新获取",(long)180-count];
    forgetPassWordLabel.font = [UIFont systemFontOfSize:12];

    [forgetPassWordLabel setText:timeStr];
    if(count == 180){
        [forgetPassWordLabel setText:@"重新获取"];
        forgetPassWordLabel.font = [UIFont systemFontOfSize:15];

    }
    
}
-(void)showRepeatButton{
    
    [_timer1 invalidate];
    return;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    [beginTextfield resignFirstResponder];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
